package com.liyiruo.springbootdruid.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.jakarta.StatViewServlet;
import com.alibaba.druid.support.jakarta.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig  {

    /**
     * 配置数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置 Druid 监控 Servlet
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        // 配置初始化参数
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin"); // 登录用户名
        initParams.put("loginPassword", "admin"); // 登录密码
        initParams.put("allow", ""); // 允许访问的IP，空表示允许所有
        initParams.put("deny", ""); // 拒绝访问的IP
        initParams.put("resetEnable", "true"); // 是否允许重置统计数据

        registrationBean.setInitParameters(initParams);
        return registrationBean;
    }

    /**
     * 配置 Druid 监控 Filter
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>(new WebStatFilter());

        // 配置过滤规则
        registrationBean.addUrlPatterns("/*");

        // 配置忽略资源
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");

        registrationBean.setInitParameters(initParams);
        return registrationBean;
    }
}

